package cn.edu.gdut.deepcode.interceptor;

import cn.edu.gdut.deepcode.utils.CommonUtils;
import cn.edu.gdut.deepcode.utils.JwtTool;
import cn.edu.gdut.deepcode.context.UserContext;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static cn.edu.gdut.deepcode.constant.AbnormalInfoConstant.LI_TOKEN_EI_2;
import static cn.edu.gdut.deepcode.constant.ReqRespConstant.*;

/**
 * <p>
 * 登录拦截器
 * </p>
 *
 * @Author: 暮倦
 * @Since: 2025-04-08  21:04
 * @Version: 1.0.0
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private final JwtTool jwtTool;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行options请求
        if (OPTIONS_METHOD_NAME.equals(request.getMethod())){
            response.setStatus(SUCCESSFUL_CODE);
            return true;
        }

        // 获取token
        String authorization = request.getHeader(AUTHORIZATION_HEADER_NAME);
        if (StrUtil.isBlank(authorization)) {
            CommonUtils.recordErrorInfoAndThrowException(
                    LI_TOKEN_EI_2,
                    authorization);
        }
        // 检验token
        try {
            // 检验成功则记录id
            Long userId = jwtTool.parseToken(authorization);
            UserContext.setUser(userId);
        } catch (Exception e) {
            CommonUtils.recordErrorInfoAndThrowException(
                    LI_TOKEN_EI_2,
                    authorization);
        }
        // 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 删除id信息
        UserContext.removeUser();
    }
}
